import {Request, Enums} from 'common-pkg'



import {useUserStore} from '@/stores/user'
import {isInvalidData} from '@/utils/utils'
import {hideLoading, loading, tip} from '@/utils/uni-api-wrap/toast'

// 前置拦截器
Request.Mp.addRequestBeforeHook(request => {
  const userStore = useUserStore()
  if (request.loading !== false) loading()
  if (!isInvalidData(userStore.token)) {
    request.headers["token"] = userStore.token
  }
  console.log('请求前', request)
})

Request.Mp.addResponseAfterHook((response, http, accessor) => {
  const userStore = useUserStore()

  if (response.request.loading !== false) {
    try { hideLoading() } catch (e) {}
  }
  //只将请求结果的data字段返回
  const { data } = response
  if (data.code === 100003 || data.code === 100004) {
    tip(data.msg || '用户信息已失效')
    // 标识当前请求为需要重复的请求
    accessor.repeatRequest = true

    // 重新登录
    userStore.loginAction().then(() => {
      accessor.task.emit(Enums.RequestEnum.ACCESSOR_REPEAT_REQUEST)
    })
  }
  console.log('响应后', response)
})

Request.Mp.addRequestErrorHook(err => {
  console.log('响应后发生错误', err)

  if (err.request.loading !== false) {
    try { hideLoading() } catch (e) {}
  }
  //发生网络错误后会走到这里
  if (err.status === 404) {
    tip(`${err.request.baseURL}${err.request.url}接口不存在`)
  } else if (err.status >= 500) {
    tip('服务器忙')
  } else {
    tip("网络出错了，请检查网络")
  }
})

export default Request.Mp.getHttpClient({
  baseURL: import.meta.env.VITE_APP_BASE_URL,
  filterResponseResult: true
})
